<!--
 * @Description: 数据库因子库列表
 * @Author: zhangchangcheng
 * @Date: 2022-01-10 16:04:17
 * @LastEditors: qingyang
 * @LastEditTime: 2023-07-19 14:36:55
-->
<template>
  <div class="factor-list-container">
    <CPageTable @register="registerPage" v-model:searchForm="searchForm">
      <template #headerRightButton>
        <div class="g-flex">
          <el-button @click="handleDownloadTemplate">
            <CIcon type="c-xian-xiazai" class="g-mr4"></CIcon>模板下载
          </el-button>
          <g-upload
            v-btnPermission="'PCF_FACTOR_BATCH_IMPORT'"
            :action="importFactorUrl"
            ref="uploadRef"
            :show-file-list="false"
            :limit="100"
            accept=".xlsx, .xls"
            @success="handleUploadSuccess"
            style="margin: 0 8px"
          >
            <template #default="{ loading: btnLoading }">
              <el-button type="primary" :loading="btnLoading"
                ><CIcon type="c-xian-daoru" class="g-mr4"></CIcon>批量导入</el-button
              >
            </template>
          </g-upload>
          <el-button @click="createFactor()" type="primary" v-btnPermission="'PCF_FACTOR_ADD'">
            <CIcon type="c-xian-xinjian" class="g-mr4"></CIcon>
            新增
          </el-button>
        </div>
      </template>
      <template #name="{ scope }">
        <CTableColumn
          :main-text="scope.row.factorName"
          :sub-text="empty(scope.row.enName)"
          is-link
          @link-click="goDetail(scope.row)"
        >
          <template #third>
            <p class="g-font-12n3">{{ empty(scope.row.factorNo) }}</p>
          </template>
        </CTableColumn>
        <!-- <CLink @click="goDetail(scope.row)">{{ scope.row.factorName }}</CLink>
        <p class="g-font-12n3">{{ empty(scope.row.enName) }}</p> -->
      </template>
      <template #categorySlot="{ scope }">
        <CTableColumn
          :main-text="FactorCategoryMap[scope.row.category]"
          :sub-text="scope.row.country"
        ></CTableColumn>
      </template>
      <template #factorSourceSlot="{ scope }">
        <CTableColumn
          :main-text="`${scope.row.emissionFactor}${scope.row.factorUnit}`"
          :sub-text="FactorSourceMap[scope.row.factorSource]"
        ></CTableColumn>
      </template>
      <template #op="{ scope }">
        <CTableButtonGroup :buttons-config="getTableButtonsConfig(scope.row)" />
      </template>
      <template #tag="{ scope }">
        <div class="model-tag-wrap" v-if="scope.row.tag">
          <div class="model-tag" v-for="(item, index) in renderTags(scope.row.tag)" :key="index">{{
            item
          }}</div>
        </div>
        <span v-else>-</span>
      </template>
      <template #comment="{ scope }">
        <p v-ellTooltip:2>{{ empty(scope.row.comment) }}</p>
      </template>
    </CPageTable>
    <importFactorDialog v-model:visible="dialogVisible" :res="res"></importFactorDialog>
    <detail v-model:visible="detailVisible" :factorNo="factorNo"></detail>
    <add-factor-dialog
      v-model:visible="addVisible"
      :info="factorInfo"
      @refresh="refresh"
    ></add-factor-dialog>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { CPageTable, useCPageTable, CPageTableProps } from '@/components/CPageTable';
import { useFactorList } from './useFactorList';
import detail from './components/detail.vue';
import AddFactorDialog from './components/AddFactor/index.vue';
import { empty } from '@/utils/index';
import { FactorCategoryMap, FactorSourceMap } from '@/constants/enum';
import { IFactorDetail } from '@/apis/pcf/database//model/factorListModel';
import type { TableButtonItem } from '@/components/CTable';
import { importFactorUrl } from '@/apis/system/database/factorList';
import { delFactor } from '@/apis/pcf/database/factorList';
import { useMessage } from '@/hooks/useMessage';
import importFactorDialog from './components/importFactorDialog.vue';
import { GUpload } from '@/components/GUpload/index';
import { CLink } from '@/components/CLink/index';
import { CTableButtonGroup, CTableColumn } from '@/components/CTable';
import { useTemplateFile } from '@/hooks/useTemplateFile';

const { createMessage, createConfirm } = useMessage();
const { handleDownloadTemplate } = useTemplateFile('FOOTPRINT_FACTOR_TEMPLATE', 'footprintFactor');
const dialogVisible = ref(false);
const res = ref();
const factorNo = ref('');
const factorInfo = ref({} as IFactorDetail | null);
const detailVisible = ref(false);
const addVisible = ref(false);

const { searchOptions, searchForm, tableOptions, tableFieldsSetting } = useFactorList();
const options = reactive<CPageTableProps>({
  title: '碳足迹因子库',
  searchOptions: searchOptions,
  tableOptions,
  tableFieldsSetting,
  enableFieldsSetting: true
});
const [registerPage, { refresh }] = useCPageTable(options);

/**
 * 配置表格的按钮
 * @param row 表格行数据
 */
function getTableButtonsConfig(row: IFactorDetail): TableButtonItem[] {
  return [
    {
      text: '编辑',
      btnPermission: 'PCF_FACTOR_EDIT',
      onClick: () => createFactor(row)
    },
    {
      text: '删除',
      btnPermission: 'PCF_FACTOR_DELETE',
      onClick: () => handleDel(row)
    }
  ];
}

const goDetail = (row: any) => {
  detailVisible.value = true;
  factorNo.value = row.factorNo;
};
const createFactor = (row?: IFactorDetail) => {
  addVisible.value = true;
  factorInfo.value = row ?? null;
};
const handleDel = async (row: IFactorDetail) => {
  createConfirm('确定删除该因子吗？', '删除后不可恢复！', {
    iconType: 'warning'
  }).then(async () => {
    await delFactor(row.factorNo);
    createMessage.success(`因子删除成功！`);
    refresh(true);
  });
};
const handleUploadSuccess = (file: any) => {
  console.log('handleUploadSuccess', file);
  refresh();
  if (file.response.data.failNum == 0) {
    createMessage.success('上传成功');
  } else {
    dialogVisible.value = true;
    res.value = file.response.data;
  }
};

const renderTags = (tag: string) => {
  if (tag) {
    return tag.split(',');
  }
  return [];
};
</script>

<style lang="scss" scoped>
.factor-list-container {
  min-height: 80%;
}
.model-tag {
  min-width: 36px;
  height: 20px;
  padding: 0 6px;
  line-height: 20px;
  text-align: center;
  background: #eef1f5;
  border-radius: 3px;
  font-size: 12px;
  color: #5a739a;
  margin-bottom: 4px;
  margin-right: 4px;
}
.model-tag-wrap {
  display: flex;
  flex-wrap: wrap;
}
</style>
